package com.acane.instagram.feature.postDetail

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.dto.CommentDTO
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class PostDetailViewModel(
    savedStateHandle: SavedStateHandle
   // private val postId: String // 通过 factory 直接传入
): ViewModel()  {
//    val initialCommentId = savedStateHandle.get<String?>(COMMENT_ID_PARAM)
    private val postId: String = checkNotNull(savedStateHandle[POST_DETAIL_ROUTE_WITH_POST_ID])

    var caption by mutableStateOf("")

    private val _postData = MutableStateFlow<PostInfo?>(null)
    val postData = _postData

//    companion object {
//        fun provideFactory(postId: String): ViewModelProvider.Factory {
//            return object : ViewModelProvider.Factory {
//                override fun <T : ViewModel> create(modelClass: Class<T>): T {
//                    return PostDetailViewModel(postId) as T
//                }
//            }
//        }
//    }


    // 改为使用CommentDTO列表
    private val _comments = MutableStateFlow<List<CommentDTO>>(emptyList())
    val comments = _comments.asStateFlow()



    init {
        loadData()
    }

    fun sendComment(comment: CommentDTO) {
        viewModelScope.launch {
            try {
                // 1. 先本地添加（临时显示）
                _comments.update { list ->
                    listOf(comment) + list // 按时间降序，新评论在前
                }

                // 2. 实际发送到服务器
                val response = MyRetrofitDatasource.createNewComment(comment)

                // 3. 成功后重新加载最新数据确保一致性
                if (response.data != null) {
                    loadComments()
                }
            } catch (e: Exception) {
                // 回滚本地添加
                _comments.update { it.filterNot { c -> c.id == comment.id } }
            }
        }
    }

//    fun loadComments() {
//        viewModelScope.launch {
//            val response = MyRetrofitDatasource.getCommentListByPostId(postId)
//            _comments.value = response.data?.sortedByDescending { it.timestamp } ?: emptyList()
//        }
//    }

//    // 修改初始化逻辑
//    private fun loadData(postId: String) {
//        loadPost(postId)
//        loadComments(postId) // 单独加载评论
//    }

    private fun loadPost(postId: String) {
        viewModelScope.launch {
            _postData.value = MyRetrofitDatasource.getPostById(postId).data
        }
    }

    // 修改加载逻辑
    private fun loadData() {
        Log.d("PostDetailViewModel", "传进来的postId是$postId")
        viewModelScope.launch {
            // 并行加载帖子和评论
            launch { loadPost(postId) }
            launch { loadComments() }
        }
    }

    fun loadComments() {
        viewModelScope.launch {
            _comments.value = MyRetrofitDatasource.getCommentListByPostId(postId)
                .data?.sortedByDescending { it.timestamp } ?: emptyList()
        }
    }




    // PostDetailViewModel.kt
    var targetCommentId by mutableStateOf<String?>(null)
        private set

    // 设置目标评论（可为空）
    fun setTargetComment(commentId: String?) {
        targetCommentId = commentId?.takeIf { it.isNotBlank() }
        Log.d("PostDetailViewModel", "点击的评论id: $targetCommentId")
    }

    // 清除目标状态
    fun clearTargetComment() {
        targetCommentId = null
    }

//    init {
//        loadData(postId)
//    }
//
//    private fun loadData(postId: String) {
//        // 加载帖子信息
//        viewModelScope.launch {
//            _postData.value = MyRetrofitDatasource.getPostById(postId).data
//        }
//        // 加载评论信息
//        viewModelScope.launch {
//            _commentData.value = MyRetrofitDatasource.getCommentListByPostId(postId).data!!
//        }
//
//    }


}